﻿<template>
  <div
    class="l-rblock learun-el-form-left"
    style="padding: 16px; overflow: hidden auto"
  >
    <el-form
      :model="formData"
      :rules="rules"
      size="mini"
      labelPosition="left"
      labelWidth="80px"
      ref="form"
    >
      <div class="l-auto-window only-tabs">
        <el-tabs v-model="activeName" type="card">
          <el-tab-pane
            class="l-tabs-container"
            :label="$t('主表信息')"
            name="tab0"
          >
            <el-row :gutter="78">
              <div class="l-rblock">
                <el-col :span="24">
                  <div class="learun-form-title">基础信息</div>
                </el-col>
                <el-col
                  v-if="lr_formLookAuth('case_erp_apply_f_Number')"
                  :span="9"
                  style="padding-right: 0"
                >
                  <el-form-item
                    :label="$t('申请单号')"
                    prop="case_erp_apply_f_Number"
                  >
                    <l-code
                      size="mini"
                      code="erp_apply_num"
                      v-model="formData.case_erp_apply_f_Number"
                      v-if="parseInt(formData.case_erp_apply_f_IsSysNum) == 0"
                    />
                    <el-input
                      v-else
                      :disabled="
                        !lr_formEditAuth(
                          'case_erp_apply_f_Number',
                          false || isReadOnly || isEdit
                        )
                      "
                      v-model="formData.case_erp_apply_f_Number"
                    />
                  </el-form-item>
                </el-col>
                <el-col
                  v-if="lr_formLookAuth('case_erp_apply_f_IsSysNum')"
                  :span="3"
                  style="padding-left: 4px"
                >
                  <el-form-item labelWidth="0" prop="case_erp_apply_f_IsSysNum">
                    <l-checkbox
                      :disabled="
                        !lr_formEditAuth(
                          'case_erp_apply_f_IsSysNum',
                          false || isReadOnly || isEdit
                        )
                      "
                      :options="case_erp_apply_f_IsSysNumOptions"
                      v-model="formData.case_erp_apply_f_IsSysNum"
                      @change="handleCodeTypeChange"
                    />
                  </el-form-item>
                </el-col>
                <el-col
                  v-if="lr_formLookAuth('case_erp_apply_f_Theme')"
                  :span="24"
                >
                  <el-form-item
                    :label="$t('申请主题')"
                    prop="case_erp_apply_f_Theme"
                  >
                    <el-input
                      :disabled="
                        !lr_formEditAuth('case_erp_apply_f_Theme', isReadOnly)
                      "
                      v-model="formData.case_erp_apply_f_Theme"
                      :placeholder="$t('请输入')"
                    >
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col
                  v-if="lr_formLookAuth('case_erp_apply_f_ApplyDate')"
                  :span="12"
                >
                  <el-form-item
                    :label="$t('申请日期')"
                    prop="case_erp_apply_f_ApplyDate"
                  >
                    <l-date
                      :disabled="
                        !lr_formEditAuth(
                          'case_erp_apply_f_ApplyDate',
                          isReadOnly
                        )
                      "
                      :readonly="false"
                      format="yyyy-MM-dd"
                      dateType="date"
                      :clearable="true"
                      v-model="formData.case_erp_apply_f_ApplyDate"
                      :placeholder="$t('请选择')"
                    />
                  </el-form-item>
                </el-col>
                <el-col
                  v-if="lr_formLookAuth('case_erp_apply_f_ApplyDep')"
                  :span="12"
                >
                  <el-form-item
                    :label="$t('申请部门')"
                    prop="case_erp_apply_f_ApplyDep"
                  >
                    <l-department-select
                      :disabled="
                        !lr_formEditAuth(
                          'case_erp_apply_f_ApplyDep',
                          isReadOnly
                        )
                      "
                      v-model="formData.case_erp_apply_f_ApplyDep"
                    />
                  </el-form-item>
                </el-col>
                <el-col
                  v-if="lr_formLookAuth('case_erp_apply_f_ApplyPerson')"
                  :span="12"
                >
                  <el-form-item
                    :label="$t('申请人员')"
                    prop="case_erp_apply_f_ApplyPerson"
                  >
                    <l-user-select
                      :disabled="
                        !lr_formEditAuth(
                          'case_erp_apply_f_ApplyPerson',
                          isReadOnly
                        )
                      "
                      v-model="formData.case_erp_apply_f_ApplyPerson"
                      isDepartment
                      :department="formData.case_erp_apply_f_ApplyDep"
                    />
                  </el-form-item>
                </el-col>
                <el-col
                  v-if="lr_formLookAuth('case_erp_apply_f_RelatedProject')"
                  :span="12"
                >
                  <el-form-item
                    :label="$t('关联项目')"
                    prop="case_erp_apply_f_RelatedProject"
                  >
                    <l-select
                      :disabled="
                        !lr_formEditAuth(
                          'case_erp_apply_f_RelatedProject',
                          false || isReadOnly
                        )
                      "
                      :options="case_erp_apply_f_RelatedProjectOptions"
                      v-model="formData.case_erp_apply_f_RelatedProject"
                    />
                  </el-form-item>
                </el-col>
                <el-col
                  v-if="lr_formLookAuth('case_erp_apply_f_Description')"
                  :span="24"
                >
                  <el-form-item
                    :label="$t('备注')"
                    prop="case_erp_apply_f_Description"
                  >
                    <el-input
                      type="textarea"
                      :disabled="
                        !lr_formEditAuth(
                          'case_erp_apply_f_Description',
                          isReadOnly
                        )
                      "
                      v-model="formData.case_erp_apply_f_Description"
                      :placeholder="$t('请输入')"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <div class="learun-form-title">{{ $t("物品明细") }}</div>
                </el-col>
                <el-col v-if="!isReadOnly" :span="12">
                  <div style="text-align: right">
                    <el-button
                      size="mini"
                      type="primary"
                      @click="handleCase_erp_saledetailAddRow"
                      >{{ $t("添加") }}</el-button
                    >
                    <el-button size="mini" type="danger" @click="deleteRows">{{
                      $t("移除")
                    }}</el-button>
                  </div>
                </el-col>

                <el-col
                  v-if="lr_formLookAuth('1670481739858_99913')"
                  :span="24"
                >
                  <l-edit-table
                    :columns="
                      lr_formTableAuth(
                        'case_erp_applydetail',
                        case_erp_apply_columns
                      )
                    "
                    :isMultiSelect="!isReadOnly"
                    :isAddBtn="false"
                    ref="mainTable"
                    :dataSource="case_erp_apply_data"
                    rowKey="f_Id"
                    @deleteRow="deleteRow"
                    :isRead="isReadOnly"
                    :summaryList="[
                      {
                        label: '总量',
                        prop: 'f_Count',
                        decimals: 0,
                      },
                      {
                        label: '总金额',
                        prop: 'f_Amount',
                      },
                    ]"
                    showSummary2
                  >
                    <template v-slot:f_Price="scope">
                      <el-input
                        @input="handleRowChange(scope.row)"
                        size="mini"
                        v-model="scope.row.f_Price"
                        :disabled="isReadOnly"
                      />
                    </template>
                    <template v-slot:f_Count="scope">
                      <el-input-number
                        controlsPosition="right"
                        size="mini"
                        v-model="scope.row.f_Count"
                        :min="0"
                        @change="handleRowChange(scope.row)"
                        :disabled="isReadOnly"
                      />
                    </template>
                    <template v-slot:f_Amount="scope">
                      <el-input
                        size="mini"
                        v-model="scope.row.f_Amount"
                        disabled
                      />
                    </template>
                    <template v-slot:f_PayDate="scope">
                      <l-date
                        :readonly="false"
                        format="yyyy-MM-dd"
                        dateType="date"
                        :clearable="true"
                        size="mini"
                        v-model="scope.row.f_PayDate"
                        :disabled="isReadOnly"
                      />
                    </template>

                    <template v-slot:f_Purpose="scope">
                      <el-input
                        size="mini"
                        v-model="scope.row.f_Purpose"
                        :disabled="isReadOnly"
                      />
                    </template>
                  </l-edit-table>
                </el-col>
                <el-col v-if="!isReadOnly || fileCount > 0" :span="24">
                  <div class="learun-form-title mt-8">
                    附件<span v-if="fileCount > 0">({{ fileCount }})</span>
                  </div>
                </el-col>
                <el-col
                  v-if="lr_formLookAuth('case_erp_apply_f_File')"
                  :span="24"
                >
                  <el-form-item prop="case_erp_apply_f_File" labelWidth="0">
                    <l-upload
                      drag
                      maxSize="10"
                      sizeType="MB"
                      :limit="3"
                      showFileList="uploadTheme1"
                      :disabled="
                        !lr_formEditAuth(
                          'case_erp_apply_f_File',
                          false || isReadOnly
                        )
                      "
                      v-model="formData.case_erp_apply_f_File"
                      @load="fileLoad"
                      @success="fileLoad"
                      @remove="fileLoad"
                    />
                  </el-form-item>
                </el-col>
              </div>
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-form>
    <!-- 表单 -->
    <l-dialog
      :visible.sync="formVisible"
      :height="800"
      :width="1000"
      @ok="handleMaterialAdd"
      @closed="handleMaterialClosed"
    >
      <l-choose-material ref="choseForm" />
    </l-dialog>
  </div>
</template>
<script>
const api = window.$api.erpcase.apply;
export default {
  props: {
    isReadOnly: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      formVisible: false,
      moduleCode: "ERP_PurchaseApplys",
      activeName: "tab0",
      formData: {
        case_erp_apply_f_Number: "", // 申请单号
        case_erp_apply_f_IsSysNum: 0, //
        case_erp_apply_f_Theme: "", // 申请主题
        case_erp_apply_f_ApplyDate: "", // 申请日期
        case_erp_apply_f_ApplyDep: "", // 申请部门
        case_erp_apply_f_ApplyPerson: "", // 申请人员
        case_erp_apply_f_RelatedProject: "", // 关联项目
        case_erp_apply_f_Description: "", // 备注
        case_erp_apply_f_File: "", // 附件
      },
      case_erp_apply_columns: [
        { prop: "f_Number", label: "物料编码", width: 100 },
        { prop: "f_Name", label: "物料名称", width: 140 },
        { prop: "f_Model", label: "规格型号", width: 80 },
        {
          prop: "f_Unit",
          label: "单位",
          width: 64,
          dataType: "dataSource",
          dataCode: "ERP_Unit",
          valueKey: "f_id",
          labelKey: "f_name",
        },
        {
          prop: "f_Price",
          label: "预计单价",
          patterns: [{ msg: "请输入数字", reg: "/^-?[0-9]+$/" }],
          width: 80,
        },
        { prop: "f_Count", required: true, label: "申请数量", width: 100 },
        { prop: "f_Amount", label: "预计金额", width: 80 },
        {
          prop: "f_PayDate",
          label: "交付日期",
          width: 156,
        },
        {
          prop: "f_Purpose",
          label: "用途",
        },
      ],
      case_erp_apply_data: [],
      rules: {
        case_erp_apply_f_Number: [{ required: true, message: "请输入" }],
        case_erp_apply_f_Theme: [{ required: true, message: "请输入" }],
        case_erp_apply_f_ApplyDate: [{ required: true, message: "请选择" }],
      },
      fileCount: 0,
      isEdit: false,
    };
  },
  computed: {
    case_erp_apply_f_IsSysNumOptions() {
      return [{ value: "0", label: "用系统编号" }];
    },
    case_erp_apply_f_RelatedProjectOptions() {
      this.lr_loadDataItem("140");
      return this.lr_dataItemOptions(this.lr_dataItem["140"]);
    },
  },
  methods: {
    handleCase_erp_saledetailAddRow() {
      this.formVisible = true;
    },
    deleteRow({ index }) {
      this.case_erp_apply_data.splice(index, 1);
    },
    deleteRows() {
      const data = this.$refs.mainTable.getSelected();
      console.log(data.length, data,'deleteRows');
      data.forEach(({ f_Id }) => {
        const index = this.case_erp_apply_data.findIndex((t) => t.f_Id == f_Id);
        console.log(index,'deleteRows1');
        this.case_erp_apply_data.splice(index, 1);
      });
      this.$refs.mainTable.reset(); // 删除选中项后需要把表格重置
    },

    async handleMaterialAdd() {
      const data = await this.$refs.choseForm.getSelectData();
      for (let i in data) {
        let point = {};
        point.f_Id = this.$uuid();
        point.f_Number = data[i].f_Number;
        point.f_Name = data[i].f_Name;
        point.f_Model = data[i].f_Model;
        point.f_Unit = data[i].f_Unit;
        point.f_PayDate = "";
        point.f_Description = "";
        point.f_Amount = 0;
        this.case_erp_apply_data.push(point);
      }
     
      this.formVisible = false;
    },
    handleMaterialClosed() {
      this.$refs.choseForm.resetForm();
    },

    // 行数据变更
    handleRowChange(row) {
      if (row.f_Price && row.f_Count) {
        row.f_Amount = (parseFloat(row.f_Price) * row.f_Count).toFixed(2);
      } else {
        row.f_Amount = 0;
      }
    },

    // 单据编码类型变更
    handleCodeTypeChange() {
      this.formData.case_erp_apply_f_Number = "";
      if (parseInt(this.formData.case_erp_apply_f_IsSysNum) != 0) {
        this.rules.case_erp_apply_f_Number.push({
          validator: this.lr_existDbFiled,
          fieldName: "f_Number",
          keyValue: () => {
            return this.formData.case_erp_apply_f_Id;
          },
          tableName: "case_erp_apply",
          keyName: "f_Id",
          trigger: "null",
        });
      } else {
        this.formData.case_erp_apply_f_IsSysNum = 1;
        this.rules.case_erp_apply_f_Number.splice(1, 1);
      }
    },

    // fileLoad
    fileLoad({ list }) {
      this.fileCount = list.length;
    },

    // 重置表单
    resetForm() {
      this.case_erp_apply_data = [];
      this.formData.case_erp_apply_f_Id = "";
      this.$formClear(this.$refs.form);
      this.activeName = "tab0";
      this.fileCount = 0;
      this.isEdit = false;
    },
    // 校验表单
    async validateForm() {
      if (!(await this.$formValidateWraper(this.$refs.form))) {
        return false;
      }

      if (this.case_erp_apply_data.length == 0) {
        this.$message({
          type: "error",
          message: this.$t("请添加物料!"),
        });
        return false;
      }

      if (!this.$refs.mainTable.validate()) {
        return false;
      }

      return true;
    },
    // 设置表单数据
    setForm(data) {
      this.$setFormData(
        this.formData,
        data.caseErpApplyEntity,
        "case_erp_apply"
      );
      this.case_erp_apply_data = data.caseErpApplydetailList;
      this.isEdit = true;
    },
    // 获取表单数据
    getForm() {
      const formData = {};
      formData.caseErpApplyEntity = this.$getFormData(
        this.formData,
        "case_erp_apply"
      );
      formData.caseErpApplydetailList = this.case_erp_apply_data;
      return formData;
    },

    async loadFormData({ keyValue /*,params,node*/ }) {
      //  keyValue 流程中相当于流程processId,params 传递参数,node 流程节点
      const data = await this.$awaitWraper(api.get(keyValue));
      if (data) {
        this.setForm(data);
        return true;
      } else {
        return false;
      }
    },

    async saveForm({ keyValue, isEdit /*,code,node*/ }) {
      // isEdit 是否更新数据, keyValue 流程中相当于流程processId,code 表示流程中的操作码,node 流程节点
      const postData = this.getForm();
      if (isEdit) {
        // 编辑
        return await this.$awaitWraper(api.update(keyValue, postData));
      } else {
        // 新增
        postData.caseErpApplyEntity.f_Id = keyValue;
        postData.caseErpApplyEntity.f_SaveState = keyValue;
        return await this.$awaitWraper(api.add(postData));
      }
    },
  },
};
</script>